import streamlit as st
import requests
import json
import time
from datetime import datetime
import os

# 设置页面配置
st.set_page_config(
    page_title="智能聊天机器人",
    page_icon="🤖",
    layout="wide"
)

# 自定义CSS样式
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
    
    :root {
        --primary-color: #4a6fa5;
        --secondary-color: #6c757d;
        --success-color: #28a745;
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --light-color: #f8f9fa;
        --dark-color: #343a40;
        --background-color: #f0f2f6;
        --chat-bg-color: #ffffff;
        --user-bg-color: #e3f2fd;
        --bot-bg-color: #f5f5f5;
    }
    
    body {
        font-family: 'Inter', sans-serif;
        background-color: var(--background-color);
    }
    
    .main-container {
        max-width: 900px;
        margin: 0 auto;
        padding: 1rem;
    }
    
    .header {
        text-align: center;
        padding: 1.5rem 0;
        margin-bottom: 2rem;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        color: white;
        box-shadow: 0 8px 20px rgba(0,0,0,0.1);
    }
    
    .header h1 {
        font-size: 2.2rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
    }
    
    .header p {
        font-size: 1rem;
        opacity: 0.95;
        margin-bottom: 0;
    }
    
    .api-key-container {
        background-color: var(--light-color);
        padding: 1.5rem;
        border-radius: 10px;
        margin-bottom: 2rem;
        border: 1px solid #e0e0e0;
    }
    
    .api-key-container h3 {
        margin-top: 0;
        color: var(--dark-color);
        font-size: 1.2rem;
        margin-bottom: 1rem;
    }
    
    .api-link {
        color: var(--primary-color);
        text-decoration: none;
        font-weight: 600;
        transition: color 0.3s ease;
    }
    
    .api-link:hover {
        color: #3a5b8f;
        text-decoration: underline;
    }
    
    .chat-container {
        background-color: var(--chat-bg-color);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        overflow: hidden;
        border: 1px solid #e0e0e0;
    }
    
    .chat-header {
        background-color: #f8f9fa;
        padding: 1rem 1.5rem;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .chat-header h3 {
        margin: 0;
        color: var(--dark-color);
        font-size: 1.1rem;
    }
    
    .clear-btn {
        background-color: transparent;
        color: var(--secondary-color);
        border: 1px solid var(--secondary-color);
        padding: 0.4rem 0.8rem;
        border-radius: 6px;
        cursor: pointer;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }
    
    .clear-btn:hover {
        background-color: var(--secondary-color);
        color: white;
    }
    
    .chat-history {
        padding: 1.5rem;
        max-height: 500px;
        overflow-y: auto;
        scroll-behavior: smooth;
    }
    
    .message {
        margin-bottom: 1rem;
        animation: fadeIn 0.3s ease-in-out;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .user-message {
        display: flex;
        justify-content: flex-end;
    }
    
    .bot-message {
        display: flex;
        justify-content: flex-start;
    }
    
    .message-content {
        max-width: 75%;
        padding: 0.8rem 1.2rem;
        border-radius: 18px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        word-wrap: break-word;
    }
    
    .user-message .message-content {
        background-color: var(--user-bg-color);
        border-bottom-right-radius: 4px;
    }
    
    .bot-message .message-content {
        background-color: var(--bot-bg-color);
        border-bottom-left-radius: 4px;
    }
    
    .message-time {
        font-size: 0.75rem;
        color: var(--secondary-color);
        margin-top: 0.25rem;
        text-align: right;
    }
    
    .bot-message .message-time {
        text-align: left;
    }
    
    .input-container {
        padding: 1.5rem;
        background-color: var(--chat-bg-color);
        border-top: 1px solid #e0e0e0;
    }
    
    .input-field {
        width: 100%;
    }
    
    .stTextArea > div > div {
        border-radius: 8px;
        border: 1px solid #ddd;
        transition: all 0.3s ease;
    }
    
    .stTextArea > div > div:focus-within {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(74, 111, 165, 0.1);
    }
    
    .send-btn {
        background-color: var(--primary-color);
        color: white;
        border: none;
        padding: 0.75rem 2rem;
        font-size: 1rem;
        font-weight: 600;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-top: 0.5rem;
        width: 100%;
    }
    
    .send-btn:hover {
        background-color: #3a5b8f;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(74, 111, 165, 0.3);
    }
    
    .send-btn:disabled {
        background-color: #cccccc;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
    }
    
    .loading-indicator {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }
    
    .loading-spinner {
        border: 3px solid #f3f3f3;
        border-top: 3px solid var(--primary-color);
        border-radius: 50%;
        width: 20px;
        height: 20px;
        animation: spin 1s linear infinite;
        margin-right: 0.5rem;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .error-message {
        background-color: rgba(220, 53, 69, 0.1);
        color: var(--danger-color);
        padding: 1rem;
        border-radius: 8px;
        margin: 1rem 0;
        border-left: 4px solid var(--danger-color);
    }
    
    .success-message {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
        padding: 1rem;
        border-radius: 8px;
        margin: 1rem 0;
        border-left: 4px solid var(--success-color);
    }
    
    .tip-box {
        background-color: rgba(255, 193, 7, 0.1);
        padding: 1rem;
        border-radius: 8px;
        border-left: 4px solid var(--warning-color);
        margin: 1rem 0;
    }
    
    .tip-box h4 {
        color: #856404;
        margin-top: 0;
        margin-bottom: 0.5rem;
    }
    
    .tip-box p {
        margin: 0;
        color: #856404;
        font-size: 0.9rem;
    }
    
    @media (max-width: 768px) {
        .message-content {
            max-width: 85%;
        }
    }
</style>
""", unsafe_allow_html=True)

# 初始化会话状态
if "messages" not in st.session_state:
    st.session_state.messages = []
    # 添加机器人的自我介绍
    st.session_state.messages.append({
        "role": "assistant",
        "content": "您好！我是您的智能助手，很高兴为您服务。我可以回答问题、提供信息或帮助您解决问题。请问有什么我可以帮助您的吗？",
        "timestamp": datetime.now().strftime("%H:%M")
    })

if "api_key" not in st.session_state:
    st.session_state.api_key = ""

if "loading" not in st.session_state:
    st.session_state.loading = False

if "error" not in st.session_state:
    st.session_state.error = None

if "recommended_questions" not in st.session_state:
    st.session_state.recommended_questions = []

if "selected_question" not in st.session_state:
    st.session_state.selected_question = ""

# 主容器
st.markdown('<div class="main-container">', unsafe_allow_html=True)

# 标题部分
st.markdown("""
<div class="header">
    <h1>🤖 智能聊天机器人</h1>
    <p>基于通义千问API的智能对话助手</p>
</div>
""", unsafe_allow_html=True)

# 在侧边栏中添加API密钥设置
with st.sidebar:
    st.markdown("""
    <style>
        .sidebar-header {
            text-align: center;
            padding: 1rem 0;
            margin-bottom: 1rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            color: white;
        }
        
        .sidebar-header h3 {
            margin: 0;
            font-size: 1.1rem;
        }
        
        .sidebar-section {
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            border: 1px solid #e0e0e0;
        }
        
        .sidebar-section h4 {
            margin-top: 0;
            margin-bottom: 0.75rem;
            color: #343a40;
            font-size: 1rem;
        }
        
        .sidebar-tip {
            background-color: rgba(255, 193, 7, 0.1);
            padding: 0.75rem;
            border-radius: 6px;
            margin-top: 0.75rem;
            font-size: 0.9rem;
        }
        
        .sidebar-tip h5 {
            margin: 0 0 0.5rem 0;
            color: #856404;
            font-size: 0.9rem;
        }
        
        .sidebar-tip p {
            margin: 0;
            color: #856404;
            font-size: 0.85rem;
        }
        
        .sidebar-link {
            color: #4a6fa5;
            text-decoration: none;
            font-weight: 500;
        }
        
        .sidebar-link:hover {
            text-decoration: underline;
        }
    </style>
    """, unsafe_allow_html=True)
    
    # 侧边栏标题
    st.markdown("""
    <div class="sidebar-header">
        <h3>🔑 API设置</h3>
    </div>
    """, unsafe_allow_html=True)
    
    # API密钥输入区域
    st.markdown('<div class="sidebar-section">', unsafe_allow_html=True)
    st.markdown('<h4>通义千问API密钥</h4>', unsafe_allow_html=True)
    
    # API密钥输入
    api_key = st.text_input(
        "",
        value=st.session_state.api_key,
        type="password",
        placeholder="请输入您的API密钥",
        label_visibility="collapsed",
        key="sidebar_api_key"
    )
    
    # 保存按钮
    save_button = st.button("保存密钥", use_container_width=True, key="sidebar_save_button")
    
    # 保存API密钥逻辑
    if save_button:
        if api_key.strip():
            st.session_state.api_key = api_key.strip()
            st.session_state.error = None
            st.sidebar.success("✅ API密钥已保存")
        else:
            st.sidebar.error("❌ 请输入有效的API密钥")
    
    # API密钥获取提示
    st.markdown("""
    <div class="sidebar-tip">
        <h5>💡 如何获取API密钥？</h5>
        <p>请访问 <a href="https://dashscope.console.aliyun.com/apiKey" class="sidebar-link" target="_blank">阿里云通义千问API</a> 注册并创建您的通义千问API密钥。</p>
    </div>
    """, unsafe_allow_html=True)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # 额外功能区域
    st.markdown('<div class="sidebar-section">', unsafe_allow_html=True)
    st.markdown('<h4>🔧 功能选项</h4>', unsafe_allow_html=True)
    
    # 清除聊天记录按钮
    clear_chat_sidebar = st.button("清除聊天记录", use_container_width=True, key="sidebar_clear_chat")
    if clear_chat_sidebar:
        st.session_state.messages = []
        st.session_state.error = None
        st.sidebar.success("✅ 聊天记录已清除")
    
    # API密钥状态显示
    st.markdown("<div style='margin-top: 1rem; font-size: 0.85rem; color: #6c757d;'>", unsafe_allow_html=True)
    if st.session_state.api_key:
        st.markdown("**🔒 API密钥状态:** 已设置")
    else:
        st.markdown("**🔒 API密钥状态:** 未设置")
    st.markdown("</div>", unsafe_allow_html=True)
    st.markdown('</div>', unsafe_allow_html=True)
    
    # 页脚信息
    st.markdown("""
    <div style='margin-top: 2rem; text-align: center; font-size: 0.8rem; color: #6c757d;'>
        © 2024 智能聊天机器人<br>
        基于通义千问API
    </div>
    """, unsafe_allow_html=True)

# 聊天界面
st.markdown('<div class="chat-container">', unsafe_allow_html=True)

# 聊天标题栏
st.markdown("""
<div class="chat-header">
    <h3>对话历史</h3>
</div>
""", unsafe_allow_html=True)

# 顶部提示信息
if not st.session_state.api_key:
    st.info("💡 请在左侧边栏设置您的通义千问API密钥以开始对话")

# 显示错误信息
if st.session_state.error:
    st.markdown(f"""
    <div class="error-message">
        <strong>❌ 错误:</strong> {st.session_state.error}
    </div>
    """, unsafe_allow_html=True)

# 聊天历史区域
st.markdown('<div class="chat-history">', unsafe_allow_html=True)

# 显示聊天记录
for message in st.session_state.messages:
    role = message["role"]
    content = message["content"]
    timestamp = message.get("timestamp", datetime.now().strftime("%H:%M"))
    
    if role == "user":
        st.markdown(f"""
        <div class="message user-message">
            <div class="message-content">
                {content}
                <div class="message-time">{timestamp}</div>
            </div>
        </div>
        """, unsafe_allow_html=True)
    else:
        st.markdown(f"""
        <div class="message bot-message">
            <div class="message-content">
                {content}
                <div class="message-time">{timestamp}</div>
            </div>
        </div>
        """, unsafe_allow_html=True)

# 加载指示器
if st.session_state.loading:
    st.markdown("""
    <div class="loading-indicator">
        <div class="loading-spinner"></div>
        <span>AI正在思考中...</span>
    </div>
    """, unsafe_allow_html=True)

st.markdown('</div>', unsafe_allow_html=True)  # 关闭聊天历史区域

# 输入区域
st.markdown('<div class="input-container">', unsafe_allow_html=True)

# 先定义所有需要的函数

def send_message():
    if not st.session_state.api_key.strip():
        st.session_state.error = "请先设置API密钥"
        return
    
    user_input = st.session_state.get("user_input", "").strip()
    if not user_input:
        st.session_state.error = "请输入消息内容"
        return
    
    # 清空之前的错误
    st.session_state.error = None
    
    # 添加用户消息到会话
    user_message = {
        "role": "user",
        "content": user_input,
        "timestamp": datetime.now().strftime("%H:%M")
    }
    st.session_state.messages.append(user_message)
    
    # 清空输入框 (使用session_state中的一个特殊键)
    st.session_state.clear_input = True
    
    # 设置加载状态
    st.session_state.loading = True
    
    try:
        # 创建一个空的AI回复占位符
        bot_message_id = len(st.session_state.messages)
        st.session_state.messages.append({
            "role": "assistant",
            "content": "",  # 初始为空，将通过流式更新
            "timestamp": datetime.now().strftime("%H:%M")
        })
        
        # 使用流式调用API
        full_response = get_streaming_qwen_response(user_input, st.session_state.api_key, bot_message_id)
        
        # 生成推荐问题
        st.session_state.recommended_questions = generate_recommended_questions(user_input, full_response)
        
    except Exception as e:
        st.session_state.error = f"API调用失败: {str(e)}"
        # 移除占位符消息
        if len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "assistant" and not st.session_state.messages[-1]["content"]:
            st.session_state.messages.pop()
    finally:
        # 重置加载状态
        st.session_state.loading = False

# 调用通义千问API (流式)
def get_streaming_qwen_response(prompt, api_key, bot_message_id):
    """
    流式调用通义千问API获取响应
    """
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    # 构建消息列表
    messages = [
        {
            "role": "system",
            "content": "你是一个有用的AI助手，回答问题要准确、友好。"
        }
    ]
    
    # 只获取除了当前正在生成的消息外的历史消息
    history_messages = []
    for i, msg in enumerate(st.session_state.messages):
        if i != bot_message_id:  # 跳过正在生成的消息
            history_messages.append(msg)
    
    # 只保留最近的10条历史消息
    for msg in history_messages[-10:]:
        messages.append({
            "role": msg["role"],
            "content": msg["content"]
        })
    
    # 添加用户消息
    messages.append({
        "role": "user",
        "content": prompt
    })
    
    # 启用流式返回
    data = {
        "model": "qwen-turbo",
        "input": {
            "messages": messages
        },
        "parameters": {
            "temperature": 0.7,
            "top_p": 0.9,
            "stream": True  # 启用流式返回
        }
    }
    
    full_response = ""
    
    # 使用stream=True进行流式请求
    try:
        with requests.post(url, headers=headers, json=data, stream=True, timeout=60) as response:
            if response.status_code != 200:
                raise Exception(f"API请求失败: 状态码 {response.status_code}, 响应内容: {response.text}")
            
            # 逐行处理流式响应
            for line in response.iter_lines():
                if line:
                    # 处理字节流
                    line_str = line.decode('utf-8')
                    
                    # 处理SSE格式的流式响应
                    if line_str.startswith('data:'):
                        line_str = line_str[5:].strip()
                    
                    try:
                        # 解析JSON
                        chunk = json.loads(line_str)
                        
                        # 检查是否包含文本增量
                        if "output" in chunk and "text" in chunk["output"]:
                            chunk_text = chunk["output"]["text"]
                            full_response += chunk_text
                            
                            # 更新会话状态中的消息内容
                            st.session_state.messages[bot_message_id]["content"] = full_response
                            
                            # 强制页面刷新以显示流式输出
                            # 使用st.rerun()确保页面更新
                            # 这是Streamlit中实现实时更新的最可靠方式
                            st.rerun()
                            
                        # 检查是否有错误
                        if "error" in chunk:
                            raise Exception(f"API错误: {chunk['error']}")
                            
                    except json.JSONDecodeError:
                        # 忽略无法解析的行
                        continue
    except Exception as e:
        raise Exception(f"流式请求失败: {str(e)}")
    
    return full_response

# 保留原有的非流式API调用函数供推荐问题使用
def get_qwen_response(prompt, api_key):
    """
    调用通义千问API获取响应
    """
    url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    messages = [
        {
            "role": "system",
            "content": "你是一个有用的AI助手，回答问题要准确、友好。"
        },
        {
            "role": "user",
            "content": prompt
        }
    ]
    
    data = {
        "model": "qwen-turbo",
        "input": {
            "messages": messages
        },
        "parameters": {
            "temperature": 0.7,
            "top_p": 0.9
        }
    }
    
    timeout = 30
    response = requests.post(url, headers=headers, json=data, timeout=timeout)
    
    if response.status_code != 200:
        raise Exception(f"API请求失败: 状态码 {response.status_code}, 响应内容: {response.text}")
    
    result = response.json()
    
    if "output" not in result or "text" not in result["output"]:
        raise Exception(f"API响应结构异常: {result}")
    
    return result["output"]["text"]

# 生成推荐问题
def generate_recommended_questions(user_query, bot_response):
    """
    根据用户查询和机器人回复生成推荐问题
    """
    if not st.session_state.api_key.strip():
        return [
            "你能做什么？",
            "如何设置API密钥？",
            "使用这个聊天机器人需要付费吗？"
        ]
    
    try:
        prompt = f"""
        基于以下对话，生成3个用户可能会继续问的后续问题。这些问题应该与对话主题相关，并且是用户可能感兴趣的自然延续。请只返回问题列表，每个问题占一行。
        
        用户问题: {user_query}
        助手回答: {bot_response}
        
        推荐问题:
        """
        
        url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {st.session_state.api_key}"
        }
        
        data = {
            "model": "qwen-turbo",
            "input": {
                "messages": [
                    {
                        "role": "system",
                        "content": "你是一个问题生成助手，擅长根据对话内容生成相关的后续问题。"
                    },
                    {
                        "role": "user",
                        "content": prompt
                    }
                ]
            },
            "parameters": {
                "temperature": 0.7,
                "top_p": 0.9
            }
        }
        
        response = requests.post(url, headers=headers, json=data, timeout=15)
        
        if response.status_code == 200:
            result = response.json()
            if "output" in result and "text" in result["output"]:
                questions_text = result["output"]["text"]
                questions = []
                for line in questions_text.strip().split("\n"):
                    question = line.strip()
                    if question and question.endswith("?"):
                        questions.append(question)
                    elif ". " in question:
                        parts = question.split(". ", 1)
                        if len(parts) > 1 and parts[1].strip().endswith("?"):
                            questions.append(parts[1].strip())
                
                if len(questions) < 3:
                    default_questions = [
                        "这个问题还有其他方面需要了解吗？",
                        "关于这个主题，您还有其他问题吗？",
                        "您想了解更多细节吗？"
                    ]
                    for q in default_questions:
                        if q not in questions:
                            questions.append(q)
                        if len(questions) >= 3:
                            break
                
                return questions[:3]
    
    except Exception as e:
        st.session_state.error = f"生成推荐问题失败: {str(e)}"
    
    return [
        "这个问题还有其他方面需要了解吗？",
        "关于这个主题，您还有其他问题吗？",
        "您想了解更多细节吗？"
    ]

# 初始化clear_input标志
if "clear_input" not in st.session_state:
    st.session_state.clear_input = False

# 实现输入框 - 使用更直接的方式处理清空
# 如果clear_input为True，使用空字符串作为默认值
initial_value = "" if st.session_state.clear_input else None

user_input = st.text_area(
    "请输入您的问题",
    value=initial_value,
    placeholder="输入您想咨询的问题...",
    label_visibility="collapsed",
    height=100,
    key="user_input",
    on_change=lambda: st.session_state.update({"user_input_submitted": True}) if st.session_state.get("user_input", "").strip() else None
)

# 重置clear_input标志
if st.session_state.clear_input:
    st.session_state.clear_input = False

# 监听回车键提交
st.session_state.user_input_submitted = st.session_state.get("user_input_submitted", False)
if st.session_state.user_input_submitted and user_input and user_input.strip() and st.session_state.api_key.strip() and not st.session_state.loading:
    st.session_state.user_input_submitted = False
    send_message()

# 发送按钮
can_send = (user_input and user_input.strip()) and st.session_state.api_key.strip() and not st.session_state.loading
send_button = st.button(
    "发送消息", 
    use_container_width=True,
    disabled=not can_send
)

# 显示推荐问题
if st.session_state.recommended_questions and not st.session_state.loading:
    st.markdown("""
    <div style="margin-top: 1rem; padding: 0.5rem 1.5rem; background-color: #f8f9fa; border-top: 1px solid #e0e0e0;">
        <p style="font-size: 0.9rem; color: #6c757d; margin-bottom: 0.75rem;">💡 您可能还想了解：</p>
    """, unsafe_allow_html=True)
    
    col1, col2, col3 = st.columns(3)
    for i, question in enumerate(st.session_state.recommended_questions[:3]):
        if i == 0:
            with col1:
                if st.button(question, use_container_width=True, key=f"recommend_1", help="点击使用此问题"):
                    st.session_state.selected_question = question
        elif i == 1:
            with col2:
                if st.button(question, use_container_width=True, key=f"recommend_2", help="点击使用此问题"):
                    st.session_state.selected_question = question
        else:
            with col3:
                if st.button(question, use_container_width=True, key=f"recommend_3", help="点击使用此问题"):
                    st.session_state.selected_question = question
    
    st.markdown('</div>', unsafe_allow_html=True)

# 处理推荐问题选择
if st.session_state.selected_question and not st.session_state.loading:
    question = st.session_state.selected_question
    st.session_state.selected_question = ""
    
    # 添加用户消息到会话
    user_message = {
        "role": "user",
        "content": question,
        "timestamp": datetime.now().strftime("%H:%M")
    }
    st.session_state.messages.append(user_message)
    
    # 设置加载状态
    st.session_state.loading = True
    
    try:
        # 创建一个空的AI回复占位符
        bot_message_id = len(st.session_state.messages)
        st.session_state.messages.append({
            "role": "assistant",
            "content": "",  # 初始为空，将通过流式更新
            "timestamp": datetime.now().strftime("%H:%M")
        })
        
        # 使用流式调用API
        full_response = get_streaming_qwen_response(question, st.session_state.api_key, bot_message_id)
        
        # 生成新的推荐问题
        st.session_state.recommended_questions = generate_recommended_questions(question, full_response)
        
    except Exception as e:
        st.session_state.error = f"API调用失败: {str(e)}"
        # 移除占位符消息
        if len(st.session_state.messages) > 0 and st.session_state.messages[-1]["role"] == "assistant" and not st.session_state.messages[-1]["content"]:
            st.session_state.messages.pop()
    finally:
        # 重置加载状态
        st.session_state.loading = False

st.markdown('</div>', unsafe_allow_html=True)  # 关闭输入容器
st.markdown('</div>', unsafe_allow_html=True)  # 关闭聊天容器



# 当发送按钮被点击时
if send_button and user_input.strip():  # 确保输入框不为空
    send_message()

# 显示使用提示
st.markdown("""
<div class="info-card">
    <h4>📋 使用说明</h4>
    <ul>
        <li>1. 请在左侧边栏设置您的通义千问API密钥</li>
        <li>2. 在输入框中输入您的问题</li>
        <li>3. 点击发送按钮获取AI回复</li>
        <li>4. 可以在左侧边栏清除聊天记录重新开始</li>
        <li>5. API密钥仅保存在当前会话中，不会被持久化存储</li>
    </ul>
</div>
""", unsafe_allow_html=True)

# 页脚
st.markdown("""
---
<div style='text-align: center; color: var(--secondary-color); font-size: 0.9rem; margin-top: 2rem;'>
    © 2024 智能聊天机器人 | 基于通义千问API
</div>
""", unsafe_allow_html=True)

st.markdown('</div>', unsafe_allow_html=True)  # 关闭主容器